import Realm from 'realm'
import Storage from './base'

class MessageStorage extends Storage{
  saveMessage(message, update = false) {
    this.query((realm)=>{
      realm.create('Message', message, update?Realm.UpdateMode.Modified:Realm.UpdateMode.All)
    })
  }

  getFriendMessageByUid(uid, fid, limit = 50){
    return this.query(realm=>{
      const messages = realm.objects('Message').filtered(`uid = ${uid} AND fid = ${fid} LIMIT (${limit})`)
      .sorted('create_time');
      return messages
    })
  }
  getMessage(hash) {
    return this.query(realm => {
      const userList = realm.objects('Message')
      const user = userList.filtered(`hash = ${hash}`)
      return user && user[0]
    })
  }
  deleteMessage(hash) {
    return this.query(async realm => {
      const user = await this.getMessage(hash)
      user && realm.delete(user)
    })
  }
}
export default new MessageStorage()
